from flask import Flask, render_template, request, redirect, url_for, flash, send_from_directory
from flask_login import LoginManager
from datetime import datetime
import os
from config import Config
import uuid

base_dir = os.path.abspath(os.path.dirname(__file__))

app = Flask(__name__)
app.config.from_object(Config)
app.config['SECRET_KEY'] = 'your-secret-key-here'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(base_dir, 'issues.db')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

# 文件上传配置
UPLOAD_FOLDER = os.path.join(base_dir, 'uploads')
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif', 'mp3', 'mp4', 'avi', 'mov'}
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

# 确保上传目录存在
os.makedirs(UPLOAD_FOLDER, exist_ok=True)

# 初始化登录管理器
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'main.login'
login_manager.login_message = '请先登录'

# 从database.py导入db
from database import db
from database import init_db

init_db(app)

# 导入模型
from models import Issue, Comment, User, Tag, Milestone, File

# 用户加载回调函数 - Flask-Login需要
@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

# 导入视图
from views import main_bp

# 注册蓝图
app.register_blueprint(main_bp)

# 创建数据库表
with app.app_context():
    db.create_all()

# 从utils导入辅助函数
from utils import allowed_file

# 提供上传文件的路由
@app.route('/uploads/<filename>')
def uploaded_file(filename):
    filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
    
    # 设置正确的Content-Type
    if filename.lower().endswith('.pdf'):
        mimetype = 'application/pdf'
    elif filename.lower().endswith(('.png', '.jpg', '.jpeg', '.gif')):
        mimetype = 'image/' + filename.rsplit('.', 1)[1].lower()
    elif filename.lower().endswith(('.mp3')):
        mimetype = 'audio/mpeg'
    elif filename.lower().endswith(('.mp4', '.avi', '.mov')):
        mimetype = 'video/' + filename.rsplit('.', 1)[1].lower()
    elif filename.lower().endswith('.txt'):
        mimetype = 'text/plain'
    else:
        mimetype = 'application/octet-stream'
    
    response = send_from_directory(app.config['UPLOAD_FOLDER'], filename, mimetype=mimetype)
    
    # 对于媒体文件（图片、音频、视频），不设置Content-Disposition为attachment，允许浏览器内联播放
    # 对于文档类型，设置为attachment，提示下载
    if mimetype.startswith(('image/', 'audio/', 'video/')):
        response.headers["Content-Disposition"] = f'inline; filename={filename}'
    else:
        response.headers["Content-Disposition"] = f'attachment; filename={filename}'
    
    return response

if __name__ == '__main__':
    app.run(debug=True)